package cn.lcj.user.service.impl;

import cn.lcj.basic.dto.LoginInfoDto;
import cn.lcj.basic.exception.BusinessException;
import cn.lcj.basic.jwt.JwtUtils;
import cn.lcj.basic.jwt.LoginData;
import cn.lcj.basic.jwt.RsaUtils;
import cn.lcj.basic.utils.*;
import cn.lcj.org.mapper.EmployeeMapper;
import cn.lcj.sys.domain.Menu;
import cn.lcj.sys.service.IMenuService;
import cn.lcj.user.constant.WxConstants;
import cn.lcj.user.domain.Logininfo;
import cn.lcj.user.domain.User;
import cn.lcj.user.domain.Wxuser;
import cn.lcj.user.mapper.LogininfoMapper;
import cn.lcj.user.mapper.UserMapper;
import cn.lcj.user.mapper.WxuserMapper;
import cn.lcj.user.service.ILogininfoService;
import cn.lcj.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.ltgfmt.Code;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
        @Autowired
        private LogininfoMapper logininfoMapper;
        @Autowired
        private RedisTemplate redisTemplate;
        @Autowired
        private WxuserMapper wxuserMapper;
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private EmployeeMapper employeeMapper;
        @Autowired
        private IMenuService menuService;
    @Override
    public Map<String, Object> AccoutLogin(LoginInfoDto loginInfoDto) {
        String account=loginInfoDto.getAccount();
        String checkPass=loginInfoDto.getCheckPass();
        Integer type=loginInfoDto.getType();
        //1.空值校验
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
                throw new BusinessException("登录信息不全，请补全");
        }
        //2.账号校验
        Logininfo logininfo=logininfoMapper.loadAccount(loginInfoDto);
        if (logininfo==null){
            throw  new BusinessException("账号错误");
        }
        //3.校验密码 --加盐加密
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if (!inputPwd.equals(logininfo.getPassword())){
            throw  new BusinessException("密码错误");
        }
        //4.检验状态--是否被禁用
        if(!logininfo.getDisable()){
            throw  new BusinessException("该账户已经被禁用，如需启用，请联系管理员");
        }
        return longininfoSuccessJwtHandler(logininfo);

    }

    @Override
    public AjaxResult WechatLogin(Map<String, String> map) {
        //发送第二个请求需要的参数code，openid，secret返回参数token，openid
        //1.准备两发送请求的地址
        String url= WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                                            .replace("SECRET",WxConstants.SECRET)
                                            .replace("CODE",map.get("code"));
        //2.使用httpUtils发送微信登录的请求：第二个请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastJson将json格式的字符串转为json对象，为了获取token与openid
        JSONObject jsonObject=JSONObject.parseObject(jsonStr);
        //参数去微信开发平台去拷贝
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //4.通过openid查T-wxuser表
        Wxuser wxuser = wxuserMapper.loadByopenId(openid);
        //4.1查到了=免密登录：返回true，token和longininfo对象
        if(wxuser!=null){
            User user = userMapper.loadById(wxuser.getUserId());
            if(user!=null){//user绑定还在
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                Map<String, Object> resultMap = longininfoSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);

            }
        }
        //4.2没有查到数据，将token与openid响应给前端，到绑定页面进行绑定
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    @Override
    public AjaxResult AccoutBinderLogin(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String access_token = map.get("access_token");
        String openid = map.get("openid");
        //一、校验
        //1.空值校验
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("手机号或者验证码不能为空");
        }
        //2.验证码是否为空（过期）获取不正确
        //2.1获取验证码
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            throw new BusinessException("验证码已过期");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("请输入正确的验证码");
        }
        //3.准备三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换Wxuser对象
        Wxuser wxuser=jsonStr2WxUser(jsonStr);
        //6.创建user对象和logininfo对象
        //可能用户以前只是通过手机号注册了没有绑定微信
        User user = userMapper.loadByPhone(phone);
        //7.添加数据库Logininfo对象 - User对象 - WxUser对象（user里面有LogininfoId、wxuser里面有userid）
            if(user==null){
                user=phone2User(phone);
                Logininfo newLogininfo=user2Logininfo(user);
                logininfoMapper.save(newLogininfo);
                user.setLogininfoId(newLogininfo.getId());
                userMapper.save(user);
            }
            wxuser.setUserId(user.getId());
            wxuserMapper.save(wxuser);
        //8.免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Map<String, Object> resultMap = longininfoSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt= StrUtils.getComplexRandomString(32);
        String pwd=StrUtils.getComplexRandomString(12);
        String md5Pwd=Md5Utils.encrypByMd5(pwd+salt);
        user.setPassword(md5Pwd);
        user.setSalt(salt);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        //jsonStr这是一个字符串，要转化为对象
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("setUnionid"));
        return wxuser;

    }

    public Map<String,Object> longininfoSuccessJwtHandler(Logininfo logininfo){
        Map<String, Object> map = new HashMap<>();//给前端传值
        LoginData loginData = new LoginData();//给jwt加密
        //1.设置logininfo
        //1.1置空密码与盐值
        logininfo.setSalt(null);
        logininfo.setPassword(null);
         map.put("logininfo", logininfo);
         loginData.setLogininfo(logininfo);
        System.out.println(logininfo);
         //2.设置管理员permission，menus
        if(logininfo.getType()==0){
            //设置permissions(多表查询)
            List<String> permissions=employeeMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置menus(多表查询)
           List<Menu> menus=employeeMapper.findMenusByLogininfoId((logininfo.getId()));
          /* //也可以直接调用无限级树来做多级查询
            List<Menu> menus = menuService.getMenuTree();*/
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //3.设置jwttoken加密logindata
        try {
            PrivateKey privateKey =RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken= JwtUtils.generateTokenExpireInMinutes(loginData,privateKey,300);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
